<template>
	<view class="handler-container">
		<view class="processing-card">
			<!-- 加载动画 -->
			<view class="loading-animation">
				<view class="spinner">
					<view class="spinner-ring"></view>
					<view class="spinner-ring"></view>
					<view class="spinner-ring"></view>
				</view>
			</view>
			
			<!-- 处理状态 -->
			<view class="status-content">
				<text class="status-title">{{ statusTitle }}</text>
				<text class="status-desc">{{ statusDesc }}</text>
			</view>
			
			<!-- 进度指示器 -->
			<view class="progress-dots">
				<view class="dot" :class="{ active: step >= 1 }"></view>
				<view class="dot" :class="{ active: step >= 2 }"></view>
				<view class="dot" :class="{ active: step >= 3 }"></view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';

	const processing = ref(false);
	const step = ref(1);
	const statusTitle = ref('正在处理');
	const statusDesc = ref('请稍候，正在为您生成文件...');

	// 更新处理状态
	const updateStatus = (newStep, title, desc) => {
		step.value = newStep;
		statusTitle.value = title;
		statusDesc.value = desc;
	};

	// 请求权限
	const requestAlbumAuthorize = () => {
		return new Promise((resolve, reject) => {
			uni.getSetting({
				success(res) {
					if (res.authSetting['scope.writePhotosAlbum']) {
						resolve();
					} else {
						uni.authorize({
							scope: 'scope.writePhotosAlbum',
							success() {
								resolve();
							},
							fail() {
								uni.showModal({
									title: '授权提示',
									content: '需要授权访问相册权限，才能保存图片，请前往设置打开权限。',
									showCancel: false,
									success() {
										reject(new Error('无权限保存图片'));
									}
								});
							}
						});
					}
				},
				fail(err) {
					reject(err);
				}
			});
		});
	};

	// 导出PDF
	const exportAsPDF = (pdfBase64Data) => {
		console.log('导出为PDF');
		updateStatus(2, '正在生成PDF', '处理文件数据中...');
		
		try {
			// 🔥 修复 base64 解码问题
			let base64 = pdfBase64Data;
			
			// 处理不同格式的 base64 数据
			if (base64.startsWith('data:application/pdf;base64,')) {
				base64 = base64.replace('data:application/pdf;base64,', '');
			} else if (base64.startsWith('data:application/pdf;filename=generated.pdf;base64,')) {
				base64 = base64.replace('data:application/pdf;filename=generated.pdf;base64,', '');
			}
			
			// 验证 base64 格式
			if (!base64 || base64.length === 0) {
				throw new Error('PDF base64 数据为空');
			}
			
			// 清理 base64 字符串，移除非法字符
			base64 = base64.replace(/[^A-Za-z0-9+/=]/g, '');
			
			// 确保 base64 长度是 4 的倍数
			while (base64.length % 4) {
				base64 += '=';
			}
			
			console.log('处理后的 base64 长度:', base64.length);
			
			updateStatus(3, '正在保存文件', '即将完成...');
			
			// 使用 wx.base64ToArrayBuffer 替代 uni.base64ToArrayBuffer
			const buffer = wx.base64ToArrayBuffer(base64);
			const fileName = `mindmap_${Date.now()}.pdf`;
			const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;

			const fs = wx.getFileSystemManager();
			return new Promise((resolve, reject) => {
				fs.writeFile({
					filePath,
					data: buffer,
					encoding: 'binary',
					success: () => {
						console.log('✅ PDF已保存到:', filePath);
						wx.openDocument({
							filePath,
							fileType: 'pdf',
							success: () => {
								resolve('PDF导出成功');
							},
							fail: (err) => {
								console.error('❌ 打开PDF失败:', err);
								resolve('PDF保存成功，但打开失败');
							}
						});
					},
					fail: (err) => {
						console.error('❌ 写PDF文件失败:', err);
						reject('PDF保存失败: ' + JSON.stringify(err));
					}
				});
			});
		} catch (error) {
			console.error('❌ PDF处理失败:', error);
			return Promise.reject('PDF处理失败: ' + error.message);
		}
	};

	// 导出图片
	const exportAsImage = async (base64Data) => {
		console.log('导出为图片');
		updateStatus(2, '正在生成图片', '处理图像数据中...');
		
		try {
			// #ifdef MP-WEIXIN
			await requestAlbumAuthorize();
			// #endif
			
			// 🔥 修复 base64 处理
			let base64 = base64Data;
			if (base64.startsWith(', '');
			}
			
			// 清理 base64 字符串
			base64 = base64.replace(/[^A-Za-z0-9+/=]/g, '');
			while (base64.length % 4) {
				base64 += '=';
			}
			
			updateStatus(3, '正在保存到相册', '即将完成...');
			
			const filePath = `${wx.env.USER_DATA_PATH}/mindmap_${Date.now()}.png`;
			// 🔥 使用 wx.base64ToArrayBuffer
			const buffer = wx.base64ToArrayBuffer(base64);

			// 写文件
			await new Promise((resolve, reject) => {
				const fs = wx.getFileSystemManager();
				fs.writeFile({
					filePath,
					data: buffer,
					encoding: 'binary',
					success() {
						resolve();
					},
					fail(err) {
						reject(err);
					}
				});
			});

			// 保存到相册
			await new Promise((resolve, reject) => {
				wx.saveImageToPhotosAlbum({
					filePath,
					success(res) {
						resolve(res);
					},
					fail(err) {
						reject(err);
					}
				});
			});

			return '图片保存成功';
		} catch (err) {
			console.error('保存图片失败:', err);
			throw '图片保存失败: ' + err.message;
		}
	};

	// 处理业务逻辑
	const handleCommand = async (cmd) => {
		const {
			req,
			api,
			params
		} = cmd;

		console.log('开始处理命令:', {
			req,
			api,
			format: params?.format,
			dataLength: params?.data?.length
		});

		try {
			let result = null;
			let message = '';

			switch (api) {
				case 'export':
					if (params.format === 'pdf') {
						console.log('开始处理PDF导出...');
						updateStatus(1, '准备导出PDF', '正在初始化...');
						message = await exportAsPDF(params.data);
					} else if (params.format === 'image') {
						console.log('开始处理图片导出...');
						updateStatus(1, '准备导出图片', '正在初始化...');
						message = await exportAsImage(params.data);
					} else {
						throw new Error('未知的导出格式: ' + params.format);
					}
					result = {
						req,
						success: true,
						message
					};
					break;
				default:
					result = {
						req,
						success: false,
						message: '未知的操作类型: ' + api
					};
			}

			console.log('处理成功，准备返回结果:', result);

			// 返回webview页面并发送结果
			uni.navigateBack({
				success: () => {
					// 延迟发送结果，确保页面已经返回
					setTimeout(() => {
						console.log('发送导出结果事件:', result);
						uni.$emit('exportResult', result);
					}, 100);
				},
				fail: (err) => {
					console.error('返回页面失败:', err);
				}
			});

		} catch (error) {
			console.error('处理命令失败:', error);
			const result = {
				req,
				success: false,
				message: error.toString()
			};
			
			console.log('处理失败，返回错误结果:', result);
			
			uni.navigateBack({
				success: () => {
					setTimeout(() => {
						uni.$emit('exportResult', result);
					}, 100);
				},
				fail: (err) => {
					console.error('返回页面失败:', err);
				}
			});
		}
	};

	onLoad((options) => {
		if (options.cmd) {
			try {
				const cmd = JSON.parse(decodeURIComponent(options.cmd));
				console.log('收到处理命令:', cmd);
				handleCommand(cmd);
			} catch (error) {
				console.error('解析命令失败:', error);
				uni.navigateBack();
			}
		} else {
			console.error('缺少命令参数');
			uni.navigateBack();
		}
	});
</script>

<style scoped>
	.handler-container {
		display: flex;
		justify-content: center;
		align-items: center;
		min-height: 100vh;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		padding: 40rpx;
	}

	.processing-card {
		background: rgba(255, 255, 255, 0.95);
		border-radius: 24rpx;
		padding: 80rpx 60rpx;
		text-align: center;
		box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
		backdrop-filter: blur(20rpx);
		min-width: 500rpx;
		animation: slideUp 0.6s ease-out;
	}

	@keyframes slideUp {
		from {
			opacity: 0;
			transform: translateY(60rpx);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.loading-animation {
		margin-bottom: 60rpx;
	}

	.spinner {
		position: relative;
		width: 120rpx;
		height: 120rpx;
		margin: 0 auto;
	}

	.spinner-ring {
		position: absolute;
		width: 100%;
		height: 100%;
		border: 6rpx solid transparent;
		border-top: 6rpx solid #667eea;
		border-radius: 50%;
		animation: spin 2s linear infinite;
	}

	.spinner-ring:nth-child(1) {
		animation-delay: 0s;
	}

	.spinner-ring:nth-child(2) {
		width: 80%;
		height: 80%;
		top: 10%;
		left: 10%;
		border-top-color: #764ba2;
		animation-delay: -0.4s;
	}

	.spinner-ring:nth-child(3) {
		width: 60%;
		height: 60%;
		top: 20%;
		left: 20%;
		border-top-color: #f093fb;
		animation-delay: -0.8s;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}
		100% {
			transform: rotate(360deg);
		}
	}

	.status-content {
		margin-bottom: 60rpx;
	}

	.status-title {
		display: block;
		font-size: 36rpx;
		font-weight: 600;
		color: #2d3748;
		margin-bottom: 16rpx;
		letter-spacing: 1rpx;
	}

	.status-desc {
		display: block;
		font-size: 28rpx;
		color: #718096;
		line-height: 1.6;
	}

	.progress-dots {
		display: flex;
		justify-content: center;
		gap: 16rpx;
	}

	.dot {
		width: 16rpx;
		height: 16rpx;
		border-radius: 50%;
		background-color: #e2e8f0;
		transition: all 0.3s ease;
	}

	.dot.active {
		background: linear-gradient(45deg, #667eea, #764ba2);
		transform: scale(1.2);
		box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
	}

	/* 响应式适配 */
	@media (max-width: 750rpx) {
		.processing-card {
			margin: 20rpx;
			padding: 60rpx 40rpx;
			min-width: auto;
		}
		
		.status-title {
			font-size: 32rpx;
		}
		
		.status-desc {
			font-size: 26rpx;
		}
	}
</style> 